03. File & Path APIs

Files & Path APIs

In this section, you will learn to:

  • Use the Files and Path APIs
  • Describe the different file open options and know when to use each

ND079 JPND C2 L02 A03 Reading And Writing Files With The Files API

Files API

The Files API is Java's Swiss Army knife for file operations. It contains static methods for doing all sorts of file operations.

Which of the following is the Java Files API not useful for?

SOLUTION: Downloading a URL from the Internet

File Open Options

When you create, read, or write a file, there are standard modes that you can use to do so. Java uses the StandardOpenOptions class to encapsulate all these modes.

Here are some of the common modes:

Option Description
READ Open a file for reading, fail if it doesn't exist.
CREATE Create a file.
CREATE_NEW Same as CREATE, but fail if the file already exists.
WRITE Open a file for writing.
APPEND Same as WRITE, but write to the end of the file.

You are allowed to use more than one option at a time.

QUIZ QUESTION::

Match each file open option to what it does:

ANSWER CHOICES:



File Open Option

What it Does

READ

CREATE

CREATE_NEW

WRITE

APPEND

DELETE_ON_CLOSE

SOLUTION:

File Open Option

What it Does

WRITE

READ

DELETE_ON_CLOSE

CREATE_NEW

CREATE

APPEND

Path API

A Path is Java's way to refer to a file on a file system:

Path p = Path.of("your/path/here");

All paths either refer to files or directories.

  • A file contains stored data or bytes.
  • A directory contains zero or more files.

All paths are either absolute or relative.

  • Absolute paths start with a forward-slash (/) (known as the root directory on Mac and Linux), or a drive name on Windows.
  • Relative paths are only meaningful relative to some other starting point. They do not start with a forward slash or drive name.

Note that the Path object in Java always uses forward-slashes to delimit the parts of the path String, even if the underlying file system uses backslashes (such as the NTFS file system on Windows).

Path API Demo

ND079 JPND C2 L02 A04 Path API Demo

QUIZ QUESTION::

Match the kind of path with its description

ANSWER CHOICES:



Kind of path

Description

Absolute path

Relative path

SOLUTION:

Kind of path

Description

Relative path

Absolute path

Which of the following are absolute paths?

SOLUTION:
  • `/`
  • `C:/Documents/Udacity/FinalProjectRubric.xls`
  • `/usr/lib/jvm/java-11-openjdk-amd64/bin/java`